class WebSocketService {
  constructor (url) {
    this.socket = new WebSocket(url)
    this.socket.addEventListener('open', () => {
      console.log('WebSocket连接成功')
    })
    this.socket.addEventListener('message', (event) => {
      console.log('WebSocket收到消息', event.data)
    })
    this.socket.addEventListener('close', () => {
      console.log('WebSocket连接关闭')
    })
  }

  send (data) {
    this.socket.send(JSON.stringify(data))
  }

  close () {
    this.socket.close()
  }
}

const WebSocketPlugin = {
  install: (app, options) => {
    const url = options.url || 'ws://localhost:8081/ws'
    const webSocketService = new WebSocketService(url)
    app.config.globalProperties.$webSocketService = webSocketService
  }
}

export default WebSocketPlugin
